package main

import (
	"encoding/base64"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jander/golog/logger"
	"github.com/kardianos/service"
	"math/big"
	"net"
	"net/http"
	"os"
	"strconv"
	"strings"
	"sync"
	"test/aes"
	"time"
)

type program struct {
	log service.Logger
	cfg *service.Config
}

const (
	CRYPT_KEY_128 = "c2hhbmdndWFuamlhLWtleQ=="
)

func (p *program) Start(s service.Service) error {
	go p.run()
	return nil
}

func (p *program) run() {
	// 代码写在这儿
	gin.SetMode(gin.DebugMode)
	//启动http服务
	routers := InitRouter()
	err := routers.Run(":8438")
	if err != nil {
		panic(err.Error())
	}
}

//路由
func InitRouter() *gin.Engine {
	router := gin.Default()
	router.Use(gin.Recovery())
	router.POST("/login", login)
	router.GET("/uuid", mac)
	return router
}

func mac(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{"code": 1, "uuid": getMacAddrs()})
}
func login(c *gin.Context) {
	account := c.Query("account")
	password := c.Query("password")
	if account == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{"code": 0, "msg": "请填写账号密码"})
		return
	}
	mac := getMacAddrs()
	time := time.Now().Unix()
	v := make(map[string]string)
	v["account"] = account
	v["password"] = password
	v["mac"] = mac
	v["time"] = strconv.FormatInt(time, 10)
	bytesJson, _ := json.Marshal(v)
	uDec, _ := base64.URLEncoding.DecodeString(CRYPT_KEY_128)
	encrypt, _ := aes.AesEncrypt(bytesJson, uDec)
	c.JSON(http.StatusOK, gin.H{"code": 1, "encrypt": encrypt, "time": time})
}

func (p *program) Stop(s service.Service) error {
	return nil
}

var wg sync.WaitGroup

func main() {
	//option := make(service.KeyValue)
	//option["Password"] = "1234qwer"
	svcConfig := &service.Config{
		Name:        "商管家安全扩展",         //服务显示名称
		DisplayName: "商管家本地基础服务",       //服务名称
		Description: "为商品管家平台提供本地安全基础", //服务描述
		//Option:      option,              //服务描述
	}

	prg := &program{}
	s, err := service.New(prg, svcConfig)
	if err != nil {
		fmt.Println(err.Error())
	}
	if len(os.Args) > 1 {
		switch os.Args[1] {
		case "install":
			x := s.Install()
			if x != nil {
				logger.Warn("error:", x.Error())
				break
			}
			logger.Info("服务安装成功")
			xs := s.Start()
			if xs != nil {
				logger.Warn("error:", xs.Error())
				break
			}
			logger.Info("服务启动成功")
			break
		case "start":
			x := s.Start()
			if x != nil {
				logger.Warn("error:", x.Error())
				break
			}
			logger.Info("服务启动成功!")
			break
		case "stop":
			x := s.Stop()
			if x != nil {
				logger.Warn("error:", x.Error())
				break
			}
			logger.Info("服务停止成功")
			break
		case "restart":
			sp := s.Stop()
			if sp != nil {
				logger.Warn("error:", sp.Error())
			}
			logger.Info("服务关闭成功!")
			st := s.Start()
			if st != nil {
				logger.Warn("error:", st.Error())
			}
			logger.Info("服务启动成功!")
			break
		case "uninstall":
			x := s.Uninstall()
			if x != nil {
				logger.Warn("error:", x.Error())
				break
			}
			logger.Info("服务卸载成功")
			break
		}
		return
	}
	err = s.Run()
	if err != nil {
		logger.Error(err)
	}
}

func getMacAddrs() (mac string) {
	netInterfaces, err := net.Interfaces()
	if err != nil {
		fmt.Printf("fail to get net interfaces: %v", err)
		return ""
	}

	for _, netInterface := range netInterfaces {
		macAddr := netInterface.HardwareAddr.String()
		if len(macAddr) == 0 {
			continue
		} else {
			mac = strings.Replace(macAddr, ":", "", -1)
			n := new(big.Int)
			n, _ = n.SetString(mac, 16)
			return n.String()
		}
	}
	return ""
}
